package com.github.xiaolyuh.redis.serializer;

import com.alibaba.fastjson.util.IOUtils;
import org.noear.snack.ONode;

import java.util.Arrays;

/**
 * FastJson 序列化方式
 *
 * @author yuhao.wang
 */
public class FastJsonRedisSerializer extends AbstractRedisSerializer {

	@Override
	public <T> byte[] serialize(T value) throws SerializationException {
		if (value == null) {
			return SerializationUtils.EMPTY_ARRAY;
		}

		try {
			return ONode.serialize(value).getBytes(IOUtils.UTF8);
		} catch (Exception e) {
			throw new SerializationException(String.format("FastJsonRedisSerializer 序列化异常: %s, 【%s】", e.getMessage(), ONode.stringify(value)), e);
		}
	}

	@Override
	public <T> T deserialize(byte[] bytes, Class<T> resultType) throws SerializationException {
		if (SerializationUtils.isEmpty(bytes)) {
			return null;
		}

		if (Arrays.equals(getNullValueBytes(), bytes)) {
			return null;
		}

		try {
			return ONode.deserialize(new String(bytes, IOUtils.UTF8), resultType);
		} catch (Exception e) {
			throw new SerializationException(String.format("FastJsonRedisSerializer 反序列化异常: %s, 【%s】", e.getMessage(), ONode.stringify(bytes)), e);
		}
	}
}